<template>
  <div class="system-settings">
    <div class="page-header">
      <h2 class="page-title">系统设置</h2>
    </div>

    <el-tabs v-model="activeTab" class="settings-tabs">
      <el-tab-pane label="基本设置" name="basic">
        <el-form
          ref="basicFormRef"
          :model="basicForm"
          :rules="basicRules"
          label-width="120px"
          class="settings-form"
        >
          <el-form-item label="系统名称" prop="systemName">
            <el-input v-model="basicForm.systemName" placeholder="请输入系统名称" />
          </el-form-item>
          <el-form-item label="系统Logo">
            <el-upload
              class="logo-uploader"
              action="#"
              :http-request="uploadLogo"
              :show-file-list="false"
              :on-success="handleLogoSuccess"
              :before-upload="beforeLogoUpload"
            >
              <img v-if="basicForm.logoUrl" :src="basicForm.logoUrl" class="logo-image" />
              <el-icon v-else class="logo-uploader-icon"><plus /></el-icon>
            </el-upload>
            <div class="upload-tip">建议尺寸: 200px × 60px，支持 PNG、JPG 格式</div>
          </el-form-item>
          <el-form-item label="系统描述" prop="description">
            <el-input
              v-model="basicForm.description"
              type="textarea"
              :rows="4"
              placeholder="请输入系统描述"
            />
          </el-form-item>
          <el-form-item label="版权信息" prop="copyright">
            <el-input v-model="basicForm.copyright" placeholder="请输入版权信息" />
          </el-form-item>
          <el-form-item label="备案信息" prop="icp">
            <el-input v-model="basicForm.icp" placeholder="请输入备案信息" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveBasicSettings">保存设置</el-button>
            <el-button @click="resetBasicForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="参数配置" name="params">
        <el-form
          ref="paramsFormRef"
          :model="paramsForm"
          label-width="180px"
          class="settings-form"
        >
          <el-form-item label="简历创建数量限制" prop="resumeLimit">
            <el-input-number v-model="paramsForm.resumeLimit" :min="1" :max="100" />
            <span class="param-desc">每个普通用户最多可创建的简历数量</span>
          </el-form-item>
          <el-form-item label="VIP用户简历数量限制" prop="vipResumeLimit">
            <el-input-number v-model="paramsForm.vipResumeLimit" :min="1" :max="1000" />
            <span class="param-desc">每个VIP用户最多可创建的简历数量</span>
          </el-form-item>
          <el-form-item label="简历模板数量限制" prop="templateLimit">
            <el-input-number v-model="paramsForm.templateLimit" :min="1" :max="100" />
            <span class="param-desc">系统最多可创建的模板数量</span>
          </el-form-item>
          <el-form-item label="简历导出格式">
            <el-checkbox-group v-model="paramsForm.exportFormats">
              <el-checkbox label="pdf">PDF</el-checkbox>
              <el-checkbox label="word">Word</el-checkbox>
              <el-checkbox label="image">图片</el-checkbox>
              <el-checkbox label="html">HTML</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="开启用户注册" prop="enableRegister">
            <el-switch v-model="paramsForm.enableRegister" />
            <span class="param-desc">是否允许新用户注册</span>
          </el-form-item>
          <el-form-item label="开启简历分享功能" prop="enableShare">
            <el-switch v-model="paramsForm.enableShare" />
            <span class="param-desc">是否允许用户分享简历</span>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveParamsSettings">保存设置</el-button>
            <el-button @click="resetParamsForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="权限管理" name="permission">
        <div class="role-header">
          <h3>角色列表</h3>
          <el-button type="primary" size="small" @click="handleAddRole">
            <el-icon><plus /></el-icon>新增角色
          </el-button>
        </div>
        
        <el-table :data="roleList" border style="width: 100%">
          <el-table-column prop="name" label="角色名称" width="180" />
          <el-table-column prop="description" label="角色描述" />
          <el-table-column prop="userCount" label="用户数量" width="100" />
          <el-table-column label="操作" width="220">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEditRole(scope.row)">
                <el-icon><edit /></el-icon>编辑
              </el-button>
              <el-button type="success" size="small" @click="handleConfigPermission(scope.row)">
                <el-icon><setting /></el-icon>配置权限
              </el-button>
              <el-button type="danger" size="small" @click="handleDeleteRole(scope.row)" :disabled="scope.row.isSystem">
                <el-icon><delete /></el-icon>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 角色对话框 -->
        <el-dialog
          v-model="roleDialogVisible"
          :title="roleDialogType === 'add' ? '新增角色' : '编辑角色'"
          width="40%"
        >
          <el-form
            ref="roleFormRef"
            :model="roleForm"
            :rules="roleRules"
            label-width="100px"
          >
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item label="角色描述" prop="description">
              <el-input
                v-model="roleForm.description"
                type="textarea"
                :rows="3"
                placeholder="请输入角色描述"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="roleDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="submitRoleForm">确认</el-button>
            </span>
          </template>
        </el-dialog>
        
        <!-- 权限配置对话框 -->
        <el-dialog
          v-model="permissionDialogVisible"
          title="配置权限"
          width="60%"
        >
          <div v-if="currentRole" class="permission-header">
            <h3>{{ currentRole.name }} - 权限配置</h3>
          </div>
          
          <el-tree
            ref="permissionTree"
            :data="permissionList"
            show-checkbox
            node-key="id"
            :default-checked-keys="checkedPermissions"
            :props="{ label: 'name', children: 'children' }"
          />
          
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="permissionDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="savePermissions">保存</el-button>
            </span>
          </template>
        </el-dialog>
      </el-tab-pane>

      <el-tab-pane label="日志管理" name="logs">
        <div class="log-header">
          <el-form :inline="true" :model="logSearchForm" class="log-search-form">
            <el-form-item label="日志类型">
              <el-select v-model="logSearchForm.type" placeholder="请选择日志类型" clearable>
                <el-option label="操作日志" value="operation" />
                <el-option label="登录日志" value="login" />
                <el-option label="系统日志" value="system" />
              </el-select>
            </el-form-item>
            <el-form-item label="操作人">
              <el-input v-model="logSearchForm.operator" placeholder="请输入操作人" clearable />
            </el-form-item>
            <el-form-item label="操作时间">
              <el-date-picker
                v-model="logSearchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchLogs">
                <el-icon><search /></el-icon>搜索
              </el-button>
              <el-button @click="resetLogSearch">
                <el-icon><refresh /></el-icon>重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        
        <el-table :data="logList" border style="width: 100%">
          <el-table-column prop="type" label="日志类型" width="120">
            <template #default="scope">
              <el-tag :type="getLogTypeTag(scope.row.type)">
                {{ getLogTypeName(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="content" label="操作内容" min-width="250" show-overflow-tooltip />
          <el-table-column prop="operator" label="操作人" width="120" />
          <el-table-column prop="ip" label="IP地址" width="150" />
          <el-table-column prop="time" label="操作时间" width="180" />
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button type="primary" size="small" @click="viewLogDetail(scope.row)">
                <el-icon><view /></el-icon>详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="logCurrentPage"
            v-model:page-size="logPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="logTotal"
            @size-change="handleLogSizeChange"
            @current-change="handleLogCurrentChange"
          />
        </div>
        
        <!-- 日志详情对话框 -->
        <el-dialog
          v-model="logDetailVisible"
          title="日志详情"
          width="60%"
        >
          <div v-if="currentLog" class="log-detail">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="日志类型">
                <el-tag :type="getLogTypeTag(currentLog.type)">
                  {{ getLogTypeName(currentLog.type) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="操作内容">{{ currentLog.content }}</el-descriptions-item>
              <el-descriptions-item label="操作人">{{ currentLog.operator }}</el-descriptions-item>
              <el-descriptions-item label="IP地址">{{ currentLog.ip }}</el-descriptions-item>
              <el-descriptions-item label="操作时间">{{ currentLog.time }}</el-descriptions-item>
              <el-descriptions-item label="操作结果">
                <el-tag :type="currentLog.status ? 'success' : 'danger'">
                  {{ currentLog.status ? '成功' : '失败' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="详细信息">
                <div class="log-detail-info">{{ currentLog.detail }}</div>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'SystemSettings',
  setup() {
    // 当前激活的标签页
    const activeTab = ref('basic')
    
    // 基本设置表单
    const basicFormRef = ref(null)
    const basicForm = reactive({
      systemName: '简历制作小程序后台管理系统',
      logoUrl: 'https://via.placeholder.com/200x60?text=Logo',
      description: '一个功能强大的简历制作小程序后台管理系统，提供简历管理、模板管理、行业数据管理等功能。',
      copyright: '© 2023 简历制作小程序后台管理系统',
      icp: '粤ICP备XXXXXXXX号'
    })
    const basicRules = {
      systemName: [{ required: true, message: '请输入系统名称', trigger: 'blur' }],
      copyright: [{ required: true, message: '请输入版权信息', trigger: 'blur' }]
    }
    
    // 参数配置表单
    const paramsFormRef = ref(null)
    const paramsForm = reactive({
      resumeLimit: 5,
      vipResumeLimit: 20,
      templateLimit: 50,
      exportFormats: ['pdf', 'word'],
      enableRegister: true,
      enableShare: true
    })
    
    // 角色管理
    const roleList = ref([
      {
        id: '1',
        name: '超级管理员',
        description: '系统最高权限，可以管理所有功能',
        userCount: 1,
        isSystem: true
      },
      {
        id: '2',
        name: '管理员',
        description: '系统管理员，可以管理大部分功能',
        userCount: 3,
        isSystem: true
      },
      {
        id: '3',
        name: '运营人员',
        description: '负责日常运营工作',
        userCount: 5,
        isSystem: false
      },
      {
        id: '4',
        name: '内容编辑',
        description: '负责内容编辑和审核',
        userCount: 8,
        isSystem: false
      }
    ])
    const roleDialogVisible = ref(false)
    const roleDialogType = ref('add') // add, edit
    const roleFormRef = ref(null)
    const roleForm = reactive({
      name: '',
      description: ''
    })
    const roleRules = {
      name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
    }
    
    // 权限管理
    const permissionDialogVisible = ref(false)
    const currentRole = ref(null)
    const permissionTree = ref(null)
    const checkedPermissions = ref([])
    const permissionList = [
      {
        id: '1',
        name: '系统管理',
        children: [
          { id: '1-1', name: '用户管理' },
          { id: '1-2', name: '角色管理' },
          { id: '1-3', name: '权限管理' },
          { id: '1-4', name: '参数设置' }
        ]
      },
      {
        id: '2',
        name: '简历管理',
        children: [
          { id: '2-1', name: '简历列表' },
          { id: '2-2', name: '简历审核' },
          { id: '2-3', name: '简历导出' }
        ]
      },
      {
        id: '3',
        name: '模板管理',
        children: [
          { id: '3-1', name: '模板列表' },
          { id: '3-2', name: '模板创建' },
          { id: '3-3', name: '模板编辑' },
          { id: '3-4', name: '模板删除' }
        ]
      },
      {
        id: '4',
        name: '行业数据管理',
        children: [
          { id: '4-1', name: '行业数据列表' },
          { id: '4-2', name: '行业数据创建' },
          { id: '4-3', name: '行业数据编辑' },
          { id: '4-4', name: '行业数据删除' }
        ]
      }
    ]
    
    // 日志管理
    const logSearchForm = reactive({
      type: '',
      operator: '',
      dateRange: []
    })
    const logList = ref([])
    const logCurrentPage = ref(1)
    const logPageSize = ref(10)
    const logTotal = ref(0)
    const logDetailVisible = ref(false)
    const currentLog = ref(null)
    
    // 初始化数据
    onMounted(() => {
      fetchLogList()
    })
    
    // 基本设置相关方法
    const uploadLogo = (options) => {
      // 模拟上传
      setTimeout(() => {
        basicForm.logoUrl = URL.createObjectURL(options.file)
        options.onSuccess()
      }, 500)
    }
    
    const handleLogoSuccess = () => {
      ElMessage.success('Logo上传成功')
    }
    
    const beforeLogoUpload = (file) => {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isJPG && !isPNG) {
        ElMessage.error('上传Logo只能是JPG或PNG格式!')
        return false
      }
      if (!isLt2M) {
        ElMessage.error('上传Logo大小不能超过2MB!')
        return false
      }
      return true
    }
    
    const saveBasicSettings = () => {
      basicFormRef.value.validate((valid) => {
        if (valid) {
          ElMessage.success('基本设置保存成功')
        }
      })
    }
    
    const resetBasicForm = () => {
      basicFormRef.value.resetFields()
    }
    
    // 参数配置相关方法
    const saveParamsSettings = () => {
      ElMessage.success('参数配置保存成功')
    }
    
    const resetParamsForm = () => {
      paramsFormRef.value.resetFields()
    }
    
    // 角色管理相关方法
    const handleAddRole = () => {
      roleDialogType.value = 'add'
      roleForm.name = ''
      roleForm.description = ''
      roleDialogVisible.value = true
    }
    
    const handleEditRole = (row) => {
      roleDialogType.value = 'edit'
      roleForm.id = row.id
      roleForm.name = row.name
      roleForm.description = row.description
      roleDialogVisible.value = true
    }
    
    const handleDeleteRole = (row) => {
      ElMessage.success(`删除角色: ${row.name}`)
    }
    
    const submitRoleForm = () => {
      roleFormRef.value.validate((valid) => {
        if (valid) {
          ElMessage.success(roleDialogType.value === 'add' ? '新增角色成功' : '编辑角色成功')
          roleDialogVisible.value = false
        }
      })
    }
    
    // 权限配置相关方法
    const handleConfigPermission = (row) => {
      currentRole.value = row
      // 模拟获取角色权限
      if (row.id === '1') {
        checkedPermissions.value = ['1-1', '1-2', '1-3', '1-4', '2-1', '2-2', '2-3', '3-1', '3-2', '3-3', '3-4', '4-1', '4-2', '4-3', '4-4']
      } else if (row.id === '2') {
        checkedPermissions.value = ['1-1', '1-2', '2-1', '2-2', '2-3', '3-1', '3-2', '3-3', '4-1', '4-2', '4-3']
      } else if (row.id === '3') {
        checkedPermissions.value = ['2-1', '2-2', '3-1', '4-1']
      } else {
        checkedPermissions.value = ['2-1', '3-1', '4-1']
      }
      permissionDialogVisible.value = true
    }
    
    const savePermissions = () => {
      const checkedKeys = permissionTree.value.getCheckedKeys()
      const halfCheckedKeys = permissionTree.value.getHalfCheckedKeys()
      const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys]
      
      ElMessage.success(`权限配置保存成功，共选择了 ${allCheckedKeys.length} 项权限`)
      permissionDialogVisible.value = false
    }
    
    // 日志管理相关方法
    const fetchLogList = () => {
      // 模拟获取日志列表
      logList.value = [
        {
          id: '1',
          type: 'operation',
          content: '新增用户: zhangsan',
          operator: '管理员',
          ip: '192.168.1.1',
          time: '2023-07-15 14:30:25',
          status: true,
          detail: '用户创建成功，ID: 1001'
        },
        {
          id: '2',
          type: 'login',
          content: '用户登录',
          operator: '张三',
          ip: '192.168.1.100',
          time: '2023-07-15 13:20:15',
          status: true,
          detail: '登录成功，用户ID: 1001'
        },
        {
          id: '3',
          type: 'system',
          content: '系统参数修改',
          operator: '管理员',
          ip: '192.168.1.1',
          time: '2023-07-15 11:45:30',
          status: true,
          detail: '修改了简历创建数量限制参数，从 5 修改为 10'
        },
        {
          id: '4',
          type: 'operation',
          content: '删除模板: IT行业简历模板',
          operator: '管理员',
          ip: '192.168.1.1',
          time: '2023-07-14 16:30:45',
          status: false,
          detail: '删除失败，该模板正在被使用'
        },
        {
          id: '5',
          type: 'login',
          content: '用户登录',
          operator: '李四',
          ip: '192.168.1.101',
          time: '2023-07-14 09:15:20',
          status: true,
          detail: '登录成功，用户ID: 1002'
        }
      ]
      logTotal.value = 5
    }
    
    const searchLogs = () => {
      logCurrentPage.value = 1
      fetchLogList()
    }
    
    const resetLogSearch = () => {
      logSearchForm.type = ''
      logSearchForm.operator = ''
      logSearchForm.dateRange = []
      searchLogs()
    }
    
    const handleLogSizeChange = (val) => {
      logPageSize.value = val
      fetchLogList()
    }
    
    const handleLogCurrentChange = (val) => {
      logCurrentPage.value = val
      fetchLogList()
    }
    
    const getLogTypeTag = (type) => {
      const map = {
        operation: 'primary',
        login: 'success',
        system: 'warning'
      }
      return map[type] || 'info'
    }
    
    const getLogTypeName = (type) => {
      const map = {
        operation: '操作日志',
        login: '登录日志',
        system: '系统日志'
      }
      return map[type] || '未知'
    }
    
    const viewLogDetail = (row) => {
      currentLog.value = row
      logDetailVisible.value = true
    }
    
    return {
      activeTab,
      basicFormRef,
      basicForm,
      basicRules,
      uploadLogo,
      handleLogoSuccess,
      beforeLogoUpload,
      saveBasicSettings,
      resetBasicForm,
      
      paramsFormRef,
      paramsForm,
      saveParamsSettings,
      resetParamsForm,
      
      roleList,
      roleDialogVisible,
      roleDialogType,
      roleFormRef,
      roleForm,
      roleRules,
      handleAddRole,
      handleEditRole,
      handleDeleteRole,
      submitRoleForm,
      
      permissionDialogVisible,
      currentRole,
      permissionTree,
      checkedPermissions,
      permissionList,
      handleConfigPermission,
      savePermissions,
      
      logSearchForm,
      logList,
      logCurrentPage,
      logPageSize,
      logTotal,
      logDetailVisible,
      currentLog,
      searchLogs,
      resetLogSearch,
      handleLogSizeChange,
      handleLogCurrentChange,
      getLogTypeTag,
      getLogTypeName,
      viewLogDetail
    }
  }
}
</script>

<style scoped>
.system-settings {
  padding: 0;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0;
}

.settings-tabs {
  margin-bottom: 20px;
}

.settings-form {
  max-width: 800px;
  margin: 0 auto;
}

.logo-uploader {
  width: 200px;
  height: 60px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.logo-uploader:hover {
  border-color: #409EFF;
}

.logo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.logo-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.upload-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 5px;
}

.param-desc {
  margin-left: 10px;
  color: #909399;
  font-size: 14px;
}

.role-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.role-header h3 {
  margin: 0;
}

.permission-header {
  margin-bottom: 20px;
}

.permission-header h3 {
  margin: 0;
}

.log-header {
  margin-bottom: 20px;
}

.log-search-form {
  display: flex;
  flex-wrap: wrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.log-detail-info {
  white-space: pre-wrap;
  word-break: break-all;
}
</style>